<?php
namespace frontend\widgets;

use frontend\models\News;
use yii\bootstrap\Widget;
use yii\behaviors\CacheableWidgetBehavior;

class NewsForMainPage extends Widget
{
    private $news;

    public function behaviors()
    {
        return [
            [
                'class' => CacheableWidgetBehavior::className(),
                'cacheDuration' => 3600,
            ],
        ];
    }
    
    public function init()
    {
        parent::init();

        $this->news = News::find()
            ->orderBy(['date_public' => SORT_DESC])
            ->limit(3)
            ->asArray()
            ->all();
    }

    public function run()
    {   
     
        if(count($this->news) != 0)
        {
            echo '<div class="container title-header">
                    <div class="row">
                        <div class="col-sm-12">
                            <a name="renovation"></a>
                            <h1>Новости</h1>
                        </div>
                    </div>
                </div>';
            echo '<div class="container news-list-container news-main-page-container">';
            foreach($this->news as $news)
            {
                echo '<a class="news-item" href="/news/' . $news['id'] . '">
                    <div class="news-item__img-container"><img src="https://storage.yandexcloud.net/' . News::BUCKET_NAME . '/' . $news['prev_img'] . '"></div>
                    <div class="news-item__date">' . \Yii::$app->formatter->asDatetime($news['date_public'], "d.MM.YYYY") . '</div>
                    <div class="news-item__content">' . \yii\helpers\StringHelper::truncate(strip_tags($news['content']), 100) . '</div>
                </a>';
            }
            echo '</div>';
        }  
        
    }


}
